//
//  UIImageLayer.m
//  Dolphin
//
//  Created by Handymood on 11-5-22.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "UIImageLayer.h"

@implementation UIImageLayer

@synthesize button_id;
@synthesize sendWebMsg;
@synthesize target_album_xml;
@synthesize value;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        sendWebMsg = FALSE;
    }
    return self;
}

-(void) initImage:(NSString *) imgPath
  useOriginalSize:(BOOL) inUseOriginalSize
        ratioMode:(int) inRatioMode
        layerInfo:(LayerInfo *) singleLayerInfo
{
    if (singleLayerInfo.ani>0) 
    {
        //NSLog(@"single layer info ani >0");
        //continue
    }
    else if(!imgPath || [imgPath length] <=4)
    {
        return;
    }
    
    if (singleLayerInfo.target_album_xml) 
    {
        target_album_xml = [[NSString alloc] initWithString:singleLayerInfo.target_album_xml];
    }
    
    //init the scroll, if necessary 
    if (singleLayerInfo != Nil) 
    {
        if (singleLayerInfo.scroll_width <= 0 || singleLayerInfo.scroll_height <= 0) 
        {
            
        }
        else
        {
            scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,singleLayerInfo.scroll_width,singleLayerInfo.scroll_height)];
            
            scrollView.bounces = TRUE;
            scrollView.showsHorizontalScrollIndicator = NO;
            scrollView.showsVerticalScrollIndicator = NO;
        }
    }
    
    type = @"IMAGE_LAYER";
    
    NSString *fileNamePrefix;
    NSString *fileNameSuffix;
    
    if ([[self getImageType:imgPath] isEqualToString:@"png"] || [[self getImageType:imgPath] isEqualToString:@"jpg"]) 
    {
        fileNamePrefix = [imgPath  substringWithRange:NSMakeRange(0, [imgPath  length] - 4)];
        fileNameSuffix = [imgPath  substringWithRange:NSMakeRange([imgPath length]-3,3)];
    }
    else if([[self getImageType:imgPath] isEqualToString:@"jpeg"])
    {
        fileNamePrefix = [imgPath  substringWithRange:NSMakeRange(0, [imgPath  length] - 5)];
        fileNameSuffix = [imgPath  substringWithRange:NSMakeRange([imgPath length]-4,4)];
    }
    
    NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileNamePrefix ofType:fileNameSuffix];
    NSData *imageData;
    
    BOOL loadImageFromWeb = FALSE;
    BOOL loadFromCacheImage = FALSE;
    
    useHitMsg = false;
    layoutMode = -1;
    loadedOver = false;
    curImgPath = imgPath;
    ratioMode = inRatioMode;
    useOriginalRect = inUseOriginalSize;
    if (singleLayerInfo.value != Nil)
    {
        NSLog(@"VALUE != NIL%@",singleLayerInfo.value);
        
        value = [[NSString alloc] initWithString:singleLayerInfo.value];
    }
    
    if (singleLayerInfo.ani>0) 
    {
        [self initWithAnimation:singleLayerInfo];
        [self addSubview:imgView];
        return;
    }
    
    UIImage *imageNormal;
     
    if([imgPath length] > 11) 
    {
        NSString *httpSuffix = [imgPath substringWithRange:NSMakeRange(0,7)];
        
        if([[httpSuffix lowercaseString] isEqualToString:@"http://"])
        {
            NSString *tempFileName = [curImgPath stringByReplacingOccurrencesOfString:@"/" withString:@""];
            tempFileName = [tempFileName stringByReplacingOccurrencesOfString:@":" withString:@""];
            
            imageNormal = [self getCachedImage:tempFileName];
            
            if(imageNormal != Nil)
            {
                loadFromCacheImage = TRUE;
            }
            else
            {
                loadImageFromWeb = YES;
                
                //add the loading indication for loading image
                activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                activityIndicator.frame = CGRectMake(self.frame.size.width/2-20, self.frame.size.height/2-20, 40.0, 40.0);
                [activityIndicator startAnimating];
                [self addSubview:activityIndicator];
                
                NSURL *url = [NSURL URLWithString:imgPath];
                imgDataBuffer = [[NSMutableData alloc] init];
                imgLoadConnect = [[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self] retain];
                [imgLoadConnect start];
            }
        }
        else
        {
            imageData = [NSData dataWithContentsOfFile:fileLocation];
        }
    }
    else
    {
        imageData = [NSData dataWithContentsOfFile:fileLocation];
    }
    
    if(!loadImageFromWeb)//load from local
    {
        if (!loadFromCacheImage) 
        {
            imageNormal = [[UIImage alloc] initWithData:imageData];
        }
        
        [self imgInitTransform:imageNormal];
        
        if (singleLayerInfo.hit_img && [singleLayerInfo.hit_img length]>4) 
        {
            NSString *fileNamePrefix2 = [singleLayerInfo.hit_img  substringWithRange:NSMakeRange(0, [singleLayerInfo.hit_img  length] - 4)];
            NSString *fileNameSuffix2 = [singleLayerInfo.hit_img  substringWithRange:NSMakeRange([singleLayerInfo.hit_img length]-3,3)];
            
            NSString *fileLocation2 = [[NSBundle mainBundle] pathForResource:fileNamePrefix2 ofType:fileNameSuffix2];
            NSData *imageData2 = [NSData dataWithContentsOfFile:fileLocation2];
            UIImage *imageNormal2 = [[UIImage alloc] initWithData:imageData2];
            
            hitOnView = [[UIImageView alloc] initWithFrame:CGRectMake(5,8,imageNormal2.size.width,imageNormal2.size.height)];
            hitOnView.image = imageNormal2; 
            hitOnView.hidden = TRUE;
        }
        
        if (scrollView) 
        {
            scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
            [scrollView addSubview:imgView];
            
            if (hitOnView) 
            {
                [scrollView addSubview:hitOnView];
            }
            
            [self addSubview:scrollView];
            
        }
        else
        {
            [self addSubview:imgView];
            
            if (hitOnView) 
            {
                [self addSubview:hitOnView];
            }
        }
        
        if (!loadFromCacheImage) //if load from cache view, then image will auto-release
        {
            [imageNormal release];
        }  
    }
}

-(void) initHitMsg:(NSString *) inMsg
{
    useHitMsg = TRUE;
    
    curTapMsg = [[NSString alloc] initWithString:inMsg];
    
//    singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
//    [self addGestureRecognizer:singleTapRecognizer];   
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    hitOnView.hidden = NO;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    double delayInSeconds = 0.15;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        hitOnView.hidden = YES;
    });
    [[NSNotificationCenter defaultCenter] postNotificationName:curTapMsg object:self];
}

//-(void) singleTapGestureCaptured:(UITapGestureRecognizer *)touch
//{    
//    [[NSNotificationCenter defaultCenter] postNotificationName:curTapMsg object:self];
//}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [imgDataBuffer setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [imgDataBuffer appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *imageNormal = [[UIImage alloc] initWithData:imgDataBuffer];
    
    [self imgInitTransform:imageNormal];
    
    if(activityIndicator)
    {
        [activityIndicator stopAnimating];
    }
    
    if (scrollView) 
    {
        scrollView.contentSize = CGSizeMake(imgView.frame.size.width, imgView.frame.size.height);
        [scrollView addSubview:imgView];
        [self addSubview:scrollView];
    }
    else
    {
        [self addSubview:imgView];
    }
    
    //cache web image
    NSString *tempFileName = [curImgPath stringByReplacingOccurrencesOfString:@"/" withString:@""];
    tempFileName = [tempFileName stringByReplacingOccurrencesOfString:@":" withString:@""];
    
    [self cacheImage:curImgPath imageName:tempFileName webImage:imageNormal];
    
    [imageNormal release];
    
    if (sendWebMsg)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"img_load_over" object:self];
    }
}

-(void) imgInitTransform:(UIImage *) imageNormal
{
    if(!imageNormal)
        return;
    
    if(useOriginalRect)
    {
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,imageNormal.size.width,imageNormal.size.height)];
        imgView.image = imageNormal;
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, imageNormal.size.width, imageNormal.size.height);
        layoutMode = -1;
    }
    else if(ratioMode == 0)//fit the size
    {
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width, self.frame.size.height)];
        imgView.image = imageNormal;
        layoutMode = 0;
    }
    else if(ratioMode == 1)//keep ratio
    {
        CGFloat scaleVal = 1.0f;
        CGPoint offsetP   ;
        CGSize  targetSize;
        
        if( imageNormal.size.width/self.frame.size.width  >=  imageNormal.size.height/self.frame.size.height)
        {
            scaleVal = self.frame.size.width/imageNormal.size.width;
        }
        else
        {
            scaleVal = self.frame.size.height/imageNormal.size.height;
        }
        
        targetSize = CGSizeMake(imageNormal.size.width*scaleVal,imageNormal.size.height*scaleVal);
        offsetP = CGPointMake((self.frame.size.width-targetSize.width)/2,(self.frame.size.height-targetSize.height)/2);
        
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(offsetP.x,offsetP.y,
                                                                targetSize.width, targetSize.height)];
        imgView.image = imageNormal;
        layoutMode = 1;
    }
    else if(ratioMode == 2)//keep ratio,clip in rect and fill
    {
        CGFloat scaleVal = 1.0f;
        CGPoint offsetP   ;
        CGSize  targetSize;
        CGSize  clipRect;
        
        if( imageNormal.size.width/imageNormal.size.height  <=  self.frame.size.width/self.frame.size.height)
        {
            clipRect = CGSizeMake(imageNormal.size.width,
                                  self.frame.size.height/self.frame.size.width*imageNormal.size.width);
            
            scaleVal = self.frame.size.width/imageNormal.size.width;
        }
        else
        {
            clipRect = CGSizeMake(self.frame.size.width/self.frame.size.height*imageNormal.size.height,
                                  imageNormal.size.height);
            scaleVal = self.frame.size.height/imageNormal.size.height;
        }
        
        targetSize = CGSizeMake(imageNormal.size.width*scaleVal,imageNormal.size.height*scaleVal);
        offsetP = CGPointMake((self.frame.size.width-targetSize.width)/2,(self.frame.size.height-targetSize.height)/2);
        
        CGImageRef imageRef = CGImageCreateWithImageInRect([imageNormal CGImage], CGRectMake(0, 0, clipRect.width,clipRect.height));                
        
        UIImage *tmpImage = [UIImage imageWithCGImage:imageRef scale:scaleVal orientation:imageNormal.imageOrientation];
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        imgView.image = tmpImage;
        
        CGImageRelease(imageRef);
        layoutMode = 2;
    }
    else
    {
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,imageNormal.size.width,imageNormal.size.height)];
        imgView.image = imageNormal;
        layoutMode = -1;
    }
    
    //SET THE COMMIT ANIMATION
    
    /*
    self.alpha = 0.0f;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5f];
    self.alpha = 1.0f;
    [UIView commitAnimations];
    */
    
    originalRect = CGRectMake(imgView.frame.origin.x, imgView.frame.origin.y,imgView.frame.size.width,imgView.frame.size.height);
    loadedOver = true;
}

-(void) initWithAnimation:(LayerInfo *) singleLayerInfo
{
    NSMutableArray *uiAniArr = [[NSMutableArray alloc] init];
    
    int innerw;
    int innerh;
    for (int i = singleLayerInfo.anistartindex; i<= singleLayerInfo.aniendindex; i++) 
    {
        if (i == singleLayerInfo.anistartindex || i== singleLayerInfo.aniendindex || i%singleLayerInfo.discrete == 0)
        {
            NSString *tempFileName;
            UIImage *image;
            if (i<10) 
            {
                tempFileName = [[NSString alloc] initWithFormat:@"%@0%d%@",singleLayerInfo.aniprefix,i,singleLayerInfo.anisuffix];
            }
            else
            {
                tempFileName = [[NSString alloc] initWithFormat:@"%@%d%@",singleLayerInfo.aniprefix,i,singleLayerInfo.anisuffix];
            }
            
            image = [UIImage imageNamed:tempFileName];
            innerw = image.size.width; 
            innerh = image.size.height;
            [uiAniArr addObject:image];
            [image release];
        }
    }
    
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,innerw,innerh)];
    imgView.animationImages = uiAniArr;

    imgView.animationDuration = singleLayerInfo.aniduration;
    imgView.animationRepeatCount = singleLayerInfo.anirepeat;
    
    [imgView startAnimating];
    
    originalRect = CGRectMake(imgView.frame.origin.x, imgView.frame.origin.y,imgView.frame.size.width,imgView.frame.size.height);
    loadedOver = true;
}

-(CGRect ) getInnerImageFrame
{
    if (imgView == Nil)
    {
        return CGRectMake(0, 0, 0, 0);
    }
    else
    {
        return imgView.frame;
    }
}

-(void) layoutAdjustWithOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    CGRect screen_rect = [[UIScreen mainScreen] bounds];
    CGFloat screen_width = screen_rect.size.width;
    CGFloat screen_height = screen_rect.size.height;
    
    if(interfaceOrientation == UIInterfaceOrientationPortrait || 
       interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        CGRect newRect = CGRectMake(0, 0, screen_width, screen_height);
        
        [self adjustSizeWithRect:newRect];
    }
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight || 
            interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        CGRect newRect = CGRectMake(0, 0,screen_height, screen_width);
        [self adjustSizeWithRect:newRect];
    }
}

-(void) adjustSizeWithRect:(CGRect ) inRect
{
    if (imgView == Nil || imgView.animationImages != Nil) 
    {
        return;
    }
    
    if (layoutMode == -1) 
    {
        imgView.frame  = CGRectMake(0, 0, inRect.size.width, inRect.size.height);
    }
    else if (layoutMode == 0) 
    {
        CGFloat scaleValW = 1.0f;
        CGFloat scaleValH = 1.0f;
        
        scaleValW = inRect.size.width/originalRect.size.width;
        scaleValH = inRect.size.height/originalRect.size.height;
        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,
                                                                originalRect.size.width*scaleValW, originalRect.size.height*scaleValH)];
    }
    else if (layoutMode == 1) 
    {
        CGFloat scaleVal = 1.0f;
        CGPoint offsetP   ;
        CGSize  targetSize;
        
        if( originalRect.size.width/originalRect.size.height >= inRect.size.width/inRect.size.height)
        {
            scaleVal = inRect.size.width/originalRect.size.width;
        }
        else
        {
            scaleVal = inRect.size.height/originalRect.size.height;
        }
        
        targetSize = CGSizeMake(originalRect.size.width*scaleVal,originalRect.size.height*scaleVal);
        offsetP = CGPointMake((inRect.size.width-targetSize.width)/2,(inRect.size.height-targetSize.height)/2);
        
        imgView.frame = CGRectMake(offsetP.x,offsetP.y,targetSize.width,targetSize.height);// imgView.frame.size.height*scaleVal);
    }
    else if (layoutMode == 2) 
    {
        CGFloat scaleVal = 1.0f;
        CGPoint offsetP   ;
        CGSize  targetSize;
        
        if( inRect.size.width/originalRect.size.width >=  inRect.size.height/originalRect.size.height)
        {
            scaleVal = inRect.size.width/originalRect.size.width;
        }
        else
        {
            scaleVal = inRect.size.height/originalRect.size.height;
        }
        
        targetSize = CGSizeMake(originalRect.size.width*scaleVal,originalRect.size.height*scaleVal);
        offsetP = CGPointMake((originalRect.size.width-targetSize.width)/2,(originalRect.size.height-targetSize.height)/2);
        
        imgView.frame = CGRectMake(offsetP.x,offsetP.y,targetSize.width, targetSize.height);
    }
    
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, inRect.size.width, inRect.size.height);
    originalRect = CGRectMake(imgView.frame.origin.x, imgView.frame.origin.y,imgView.frame.size.width,imgView.frame.size.height);
}

-(UIImage *) getCurrentUIImage
{
    if (imgView != Nil) 
    {
        return imgView.image;
    }
    else
    {
        return Nil;
    }
}

- (void) cacheImage: (NSString *) imageURLString 
          imageName:(NSString *)imageName
           webImage:(UIImage *)inImage
{
    //Get Cache Path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    
    NSString *filePath = [paths objectAtIndex:0];
    
    // Make up the full path with file name
    NSString *fullImagePath = [filePath stringByAppendingPathComponent: imageName];
	
    // Check for file existence
    if(![[NSFileManager defaultManager] fileExistsAtPath: fullImagePath])
    {
        // Fetch image
        UIImage *image = inImage;
        
        //SAVE IMAGE WITH TYPE
        if([imageURLString rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
        {
            [UIImagePNGRepresentation(image) writeToFile: fullImagePath atomically: YES];
        }
        else if([imageURLString rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound || 
                [imageURLString rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound)
        {
            [UIImageJPEGRepresentation(image, 100) writeToFile: fullImagePath atomically: YES];
        }
    }
    
}

- (UIImage *) getCachedImage:(NSString *)imageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    
    NSString *filePath = [paths objectAtIndex:0];
    
    NSString *fullImagePath = [filePath stringByAppendingPathComponent: imageName];
    
    UIImage *image;
    
    // Check for a cached version
    if([[NSFileManager defaultManager] fileExistsAtPath: fullImagePath])
    {
        image = [UIImage imageWithContentsOfFile: fullImagePath]; // this is the cached image
    }
    else
    {
        //not found
        image = Nil;
    }
    
    return image;
}

-(NSString *) getImageType:(NSString *) inImageFileName
{
    if([inImageFileName rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
    {
        return @"png";
    }
    else if([inImageFileName rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound)
    {
        return @"jpg";
    }
    else if([inImageFileName rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound)
    {
        return @"jpeg";
    }
    else
    {
        return @"";
    }
}

-(void) reset
{
    self.userInteractionEnabled = FALSE;
    
    if (useHitMsg) 
    {
        [self removeGestureRecognizer:singleTapRecognizer];
        singleTapRecognizer.enabled = FALSE;
        [singleTapRecognizer removeTarget:self action:@selector(singleTapGestureCaptured:)];
        [singleTapRecognizer release];
        [curTapMsg release];
    }
    
    if(activityIndicator)
    {
        [activityIndicator release];
        [activityIndicator removeFromSuperview];
    }
    
    if(imgView && loadedOver)
    {
        /*
        if (imgView.animationImages != Nil) 
        {
            [imgView.animationImages release];
        }
        */
        
        [imgView removeFromSuperview];
        [imgView release];
    }
    
    if (hitOnView) 
    {
        [hitOnView removeFromSuperview];
        [hitOnView release];
    }
    
    if(imgLoadConnect)
    {
        [imgLoadConnect cancel];
        [imgLoadConnect release];
    }
    
    if (imgDataBuffer) 
    {
        [imgDataBuffer setLength:0];
        [imgDataBuffer release];
    }
    
    if (scrollView) 
    {
        [scrollView removeFromSuperview];
        [scrollView release];
    }
    
    for (UIView*singleView in[self subviews]) 
    {
        [singleView removeFromSuperview];
    }
}

@end
